"""
账户管理器模块 - 负责统一管理多个证券账户
"""
import json
import os
from typing import Dict, List, Optional, Tuple, Any
from utils.security_utils import secure_load_credentials, secure_save_credentials
from utils.exception_handler import handle_exception


class AccountManager:
    """
    账户管理器类，用于统一管理多个证券账户及其凭证
    """
    def __init__(self):
        """
        初始化账户管理器
        """
        # 存储所有账户信息 {account_id: account_info}
        self.accounts: Dict[str, Dict[str, Any]] = {}
        # 当前活跃账户ID
        self.active_account_id: Optional[str] = None
        # 账户配置文件路径
        self.accounts_config_path = os.path.join('config', 'accounts_config.json')
        # 加载已保存的账户信息
        self.load_accounts()
        
    def load_accounts(self) -> None:
        """
        从配置文件加载所有账户信息
        """
        try:
            if os.path.exists(self.accounts_config_path):
                with open(self.accounts_config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.accounts = config.get('accounts', {})
                    self.active_account_id = config.get('active_account_id')
                    # 确保活跃账户ID存在于账户列表中
                    if self.active_account_id and self.active_account_id not in self.accounts:
                        self.active_account_id = next(iter(self.accounts.keys()), None) if self.accounts else None
                
            # 初始化时，如果没有账户，创建一个默认账户
            if not self.accounts:
                default_account = {
                    'account_id': 'default',
                    'platform': 'tencent',
                    'account_name': '默认账户',
                    'description': '系统默认账户'
                }
                self.accounts[default_account['account_id']] = default_account
                self.active_account_id = default_account['account_id']
                self.save_accounts()
                
        except Exception as e:
            handle_exception(e, "加载账户配置失败")
    
    def save_accounts(self) -> None:
        """
        保存所有账户信息到配置文件
        """
        try:
            config = {
                'accounts': self.accounts,
                'active_account_id': self.active_account_id
            }
            
            # 确保config目录存在
            os.makedirs(os.path.dirname(self.accounts_config_path), exist_ok=True)
            
            with open(self.accounts_config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
                
        except Exception as e:
            handle_exception(e, "保存账户配置失败")
    
    def add_account(self, platform: str, account_name: str, api_key: str, api_secret: str, 
                   description: str = "") -> Tuple[bool, str]:
        """
        添加一个新的证券账户
        
        Args:
            platform: 平台类型，如'tencent'
            account_name: 账户名称
            api_key: API密钥
            api_secret: API密钥密码
            description: 账户描述
            
        Returns:
            Tuple[bool, str]: (是否成功, 消息/账户ID)
        """
        try:
            # 生成唯一账户ID
            account_id = f"{platform}_{len(self.accounts) + 1}"
            
            # 保存API凭证
            credentials_saved = secure_save_credentials(account_id, api_key, api_secret)
            if not credentials_saved:
                return False, "保存API凭证失败"
            
            # 添加账户信息
            self.accounts[account_id] = {
                'account_id': account_id,
                'platform': platform,
                'account_name': account_name,
                'description': description,
                'created_at': str(os.path.getmtime(self.accounts_config_path)) 
                if os.path.exists(self.accounts_config_path) else str(os.path.getctime(self.accounts_config_path))
            }
            
            # 保存账户配置
            self.save_accounts()
            
            # 如果是第一个账户，设为活跃账户
            if len(self.accounts) == 1:
                self.active_account_id = account_id
                self.save_accounts()
                
            return True, account_id
            
        except Exception as e:
            handle_exception(e, "添加账户失败")
            return False, str(e)
    
    def delete_account(self, account_id: str) -> Tuple[bool, str]:
        """
        删除指定账户
        
        Args:
            account_id: 账户ID
            
        Returns:
            Tuple[bool, str]: (是否成功, 消息)
        """
        try:
            if account_id not in self.accounts:
                return False, "账户不存在"
            
            # 删除账户信息
            del self.accounts[account_id]
            
            # 如果删除的是活跃账户，切换到第一个可用账户
            if self.active_account_id == account_id:
                self.active_account_id = next(iter(self.accounts.keys()), None) if self.accounts else None
            
            # 保存账户配置
            self.save_accounts()
            
            # 删除关联的凭证文件
            credentials_path = os.path.join('config', f'{account_id}_credentials.json')
            if os.path.exists(credentials_path):
                os.remove(credentials_path)
                
            return True, "账户已成功删除"
            
        except Exception as e:
            handle_exception(e, "删除账户失败")
            return False, str(e)
    
    def update_account(self, account_id: str, **kwargs) -> Tuple[bool, str]:
        """
        更新账户信息
        
        Args:
            account_id: 账户ID
            **kwargs: 要更新的账户信息字段
            
        Returns:
            Tuple[bool, str]: (是否成功, 消息)
        """
        try:
            if account_id not in self.accounts:
                return False, "账户不存在"
            
            # 更新账户信息
            for key, value in kwargs.items():
                if key in self.accounts[account_id] and key != 'account_id':
                    self.accounts[account_id][key] = value
            
            # 保存账户配置
            self.save_accounts()
            
            return True, "账户信息已成功更新"
            
        except Exception as e:
            handle_exception(e, "更新账户信息失败")
            return False, str(e)
    
    def switch_account(self, account_id: str) -> Tuple[bool, str]:
        """
        切换到指定账户
        
        Args:
            account_id: 账户ID
            
        Returns:
            Tuple[bool, str]: (是否成功, 消息)
        """
        try:
            if account_id not in self.accounts:
                return False, "账户不存在"
            
            # 切换活跃账户
            self.active_account_id = account_id
            
            # 保存账户配置
            self.save_accounts()
            
            return True, f"已切换到账户: {self.accounts[account_id]['account_name']}"
            
        except Exception as e:
            handle_exception(e, "切换账户失败")
            return False, str(e)
    
    def get_active_account(self) -> Optional[Dict[str, Any]]:
        """
        获取当前活跃账户信息
        
        Returns:
            Optional[Dict[str, Any]]: 活跃账户信息
        """
        if not self.active_account_id or self.active_account_id not in self.accounts:
            return None
        
        return self.accounts[self.active_account_id]
    
    def get_all_accounts(self) -> List[Dict[str, Any]]:
        """
        获取所有账户列表
        
        Returns:
            List[Dict[str, Any]]: 账户列表
        """
        return list(self.accounts.values())
    
    def get_account_by_id(self, account_id: str) -> Optional[Dict[str, Any]]:
        """
        通过ID获取账户信息
        
        Args:
            account_id: 账户ID
            
        Returns:
            Optional[Dict[str, Any]]: 账户信息
        """
        return self.accounts.get(account_id)
        
    def get_account(self, account_id: str) -> Optional[Dict[str, Any]]:
        """
        获取指定账户信息
        
        Args:
            account_id: 账户ID
            
        Returns:
            Optional[Dict[str, Any]]: 账户信息
        """
        # 直接调用get_account_by_id方法，保持方法功能一致性
        return self.get_account_by_id(account_id)
    
    def get_active_account_credentials(self) -> Tuple[Optional[str], Optional[str]]:
        """
        获取当前活跃账户的API凭证
        
        Returns:
            Tuple[Optional[str], Optional[str]]: (API Key, API Secret)
        """
        if not self.active_account_id:
            return None, None
        
        return secure_load_credentials(self.active_account_id)
    
    def update_account_credentials(self, account_id: str, api_key: str, api_secret: str) -> bool:
        """
        更新指定账户的API凭证
        
        Args:
            account_id: 账户ID
            api_key: 新的API Key
            api_secret: 新的API Secret
            
        Returns:
            bool: 是否成功
        """
        if account_id not in self.accounts:
            return False
        
        return secure_save_credentials(account_id, api_key, api_secret)


# 创建全局账户管理器实例
account_manager = AccountManager()